<template>
	<el-aside :style="{width: navMenuCollapse ? widthCollapse : width, backgroundColor:backgroundColor}" class="aside">
		<!-- #ifdef VUE2 -->
		<el-image class="headImg" fit='contain' :style="{width: navMenuCollapse ? widthCollapse : width}"
			:src="getH5 +'/static/logo.png'"></el-image>
		<!-- #endif -->
		<!-- #ifdef VUE3 -->
		<el-image class="headImg" fit='contain' :style="{width: navMenuCollapse ? widthCollapse : width}"
			:src="getH5 +'/static/logo.png'"></el-image>
		<!-- #endif -->

		<view class="search-menu-box" v-if="showMenuSeach">
			<el-autocomplete popper-class="my-autocomplete" class="inline-input w-50" value-key="text"
				v-model="searchMenuState" :fetch-suggestions="searchMenu" @select="searchMenuSelect" clearable
				placeholder="菜单搜索:名称、路径">
				<template #suffix>
					<el-icon>
						<Search />
					</el-icon>
				</template>
				<template #default="{item}">
					<!-- <el-icon>
						<component :is="item.icon"></component>
					</el-icon> -->
					<i :class="item.icon" class="icon-margin"></i>
					<span> {{ item.text }} </span>
				</template>
			</el-autocomplete>
		</view>
		<el-menu :unique-opened="true" :default-active="activeMenuIndex" :text-color="menuTextColor"
			:active-text-color="menuActiveTextColor" :background-color="backgroundColor" class="menu" @select="select"
			:collapse="navMenuCollapse">
			<el-menu-item :index="homeMenu.menu_id">
				<i :class="homeMenu.icon" class="icon-margin"></i>
				<span class="title">{{homeMenu.text }}</span>
			</el-menu-item>
			<template v-if="loaded" v-for="item in userMenu" :key="item.menu_id">
				<el-menu-item v-if="!item.children || !item.children.length" :index="item.menu_id">
					<i :class="item.icon" class="icon-margin"></i>
					<span class="title">{{item.text }}</span>
				</el-menu-item>
				<el-sub-menu v-else :index="item.menu_id">
					<template #title>
						<i :class="item.icon" class="icon-margin"></i>
						<span class="title">{{ item.text }}</span>
					</template>
					<sub-menu :data="item.children"></sub-menu>
				</el-sub-menu>
			</template>
			<!-- 隐藏静态路由 -->
			<template v-if="false" v-for="item in staticMenu" :key="item.menu_id">
				<el-menu-item v-if="!item.children || !item.children.length" :index="item.menu_id">
					<i :class="item.icon" class="icon-margin"></i>
					<span class="title">{{item.text }}</span>
				</el-menu-item>
				<el-sub-menu v-else :index="item.menu_id">
					<template #title>
						<i :class="item.icon" class="icon-margin"></i>
						<span class="title">{{ item.text }}</span>
					</template>
					<sub-menu :data="item.children"></sub-menu>
				</el-sub-menu>
			</template>
		</el-menu>
	</el-aside>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex'
	import config from '@/admin.config.js'
	import {
		buildMenus
	} from '@/components/uni-data-menu/util.js'

	import {
		debounce,
	} from '@/js_sdk/uni-stat/util.js'
	export default {
		data() {
			return {
				...config.sideBar,
				currentMenu: '/',
				homeMenu: {
					menu_id: "home",
					text: '系统首页',
					icon: 'el-icon-s-home',
					value: "/",
				},
				subMenuChildrens: [],
				loading: false,
				userMenu: [],
				isMounted: false,
				loaded: false,
				searchMenuState: "",
				getH5: uni.getStorageSync("getH5")
			}
		},

		computed: {
			...mapState('app', ['inited', 'navMenu', 'active',
				'navMenuCollapse', 'dynamicMenuItems', 'activeMenuIndex'
			]),
			userInfo() {
				return uni.getStorageSync("userInfo")
			},
		},
		watch: {
			// #ifdef H5
			$route: {
				immediate: true,
				handler(newRoute, oldRoute) {
					if (newRoute) {
						const path = newRoute.fullPath
						if (path) {
							this.currentMenu = this.splitFullPath(path)
						}
						// 登录时，重新加载左侧menu
						if (path == config.index.url) {
							this.$nextTick(function() {
								this.load()
								if (uni.getStorageSync("islogin")) {
									uni.setStorageSync("islogin", false);
									this.reload(path)
								}
							})
						}
					}

				}
			},
			// #endif
			userInfo: {
				handler(newVal, oldVal) {
					if (newVal) {
						// 当用户信息发生变化后，重新加载左侧menu
						this.$nextTick(function() {
							this.load()
						})
					}
				}
			},
			navMenuCollapse: {
				// immediate: true,
				// deep:true,
				handler(newVal, oldVal) {
					// #ifdef H5
					this.$nextTick(() => {
						if (newVal) {
							uni.setLeftWindowStyle({
								width: this.widthCollapse
							})
						} else {
							uni.setLeftWindowStyle({
								width: this.width
							})
						}
					})
					// #endif
				}
			},
			activeMenuIndex: {
				// immediate: true,
				handler(newVal, oldVal) {
					// #ifdef H5
					if (newVal) {
						this.$nextTick(() => {
							this.setRoutes(this.findRoutes([].concat(this.userMenu, this.staticMenu), newVal))
						})
					}
					// #endif
				}
			},
		},
		created() {
			this.subMenuChildrens.push(this.homeMenu)
			this.load()
			this.pushSubmenuChildren(this.staticMenu) //静态写入
			this.debounceRedirectTo = debounce((url) => {
				uni.redirectTo({
					url,
					fail: () => {
						uni.showModal({
							title: '提示',
							content: '页面 ' + url + ' 跳转失败',
							showCancel: false
						})
					}
				})
			}, 300);

			if (this.hasLocalData(this.localdata)) return

		},
		mounted() {
			this.isMounted = true
		},
		methods: {
			...mapActions({
				setRoutes: 'app/setRoutes'
			}),
			...mapMutations('app', ['ADD_DYNAMIC_MENU_ITEM', 'SET_ACTIVE_MENU_INDEX', 'SET_DYNAMIC_MENU_ITEM']),
			select(index, indexPath) {
				// console.log("index:", index, "  indexPath: ", indexPath);
				let menuItem = this.subMenuChildrens.filter((item) => item.menu_id == index)
				// console.log("clickMenuItem:", menuItem);
				this.clickMenuItem(menuItem[0])

				let routes = this.findRoutes([].concat(this.userMenu, this.staticMenu), index);
				// console.log("routes", routes);
				this.setRoutes(routes)
				// let url = e.value
				// if (!url) {
				// 	url = this.active
				// }
				// this.clickMenuItem(url)
				// // this.setRoutes(routes)
				// #ifdef H5
				// #ifdef VUE3
				uni.hideLeftWindow()
				// #endif
				// #endif
			},
			clickMenuItem(menu) {
				// console.log("clickMenuItem:", menu);
				let url = menu.value
				if (!url) {
					url = "/"
				}
				// #ifdef H5
				if (url.indexOf('http') === 0) {
					return window.open(url)
				}
				// #endif

				// url 开头可用有 / ，也可没有
				if (url[0] !== '/' && url.indexOf('http') !== 0) {
					url = '/' + url
				}
				// #ifndef H5
				if (url === "/") {
					url = config.index.url;
				}
				// #endif
				//放入到动态菜单
				if (this.homeMenu.menu_id != menu.menu_id) {
					this.ADD_DYNAMIC_MENU_ITEM(menu)
					this.SET_ACTIVE_MENU_INDEX(menu.menu_id)
				}

				// TODO 后续要调整
				this.debounceRedirectTo(url)
			},
			splitFullPath(path) {
				if (!path) {
					path = '/'
				}
				return path.split('?')[0]
			},
			filterArray(arr, role) {
				let result = []
				arr.filter(item => {
					if (item.roles && item.roles.includes(role)) {
						result.push(item);
					}
					if (Array.isArray(item.children) && item.children[0]) {
						item.children = this.filterArray(item.children, role);
					}
				})
				return result;
			},
			hasLocalData(value) {
				return Array.isArray(value) && value.length > 0
			},
			filterRoutes(menus, indexPath) {
				let routes = [];
				indexPath.forEach((index) => {
					if (Array.isArray(menus)) {
						menus = menus.filter(item => {
							if (item.menu_id == index) {
								routes.push({
									name: item.text,
									value: item.value || item.url,
									menu_id: item.menu_id,
									icon: item.icon
								});
							}
							return item.menu_id == index;
						})
						if (menus.length > 0) {
							menus = menus[0].children
						}
					}
				})
				return routes;
			},

			findRoutes(menus, index) {
				let routes = [];
				const getRoute = function(menus, index, routes) {
					for (var i = 0; i < menus.length; i++) {
						let menu = menus[i];
						if (menu.menu_id == index) {
							routes.push({
								name: menu.text,
								value: menu.value || menu.url,
								menu_id: menu.menu_id,
								icon: menu.icon
							});
							return true;
						} else if (menu.children && menu.children.length > 0) {
							if (getRoute(menu.children, index, routes)) {
								routes.push({
									name: menu.text,
									value: menu.value || menu.url,
									menu_id: menu.menu_id,
									icon: menu.icon
								});
								return true;
							}
						}
					}
					return false;
				}
				getRoute(menus, index, routes)
				routes.reverse();
				// console.log(" getRoute: ", routes);
				return routes;
			},

			pushSubmenuChildren(menus) {
				if (Array.isArray(menus)) {
					menus.forEach((item, index) => {
						if (item.children && item.children.length > 0) {
							this.pushSubmenuChildren(item.children)
						} else {
							this.subMenuChildrens.push(item)
						}
					})
				} else {
					this.subMenuChildrens.push(menus)
				}
			},
			getUserMenu(menuList) {
				const {
					permission,
					role
				} = {}
				// uniCloud.getCurrentUserInfo()
				// 标记叶子节点
				menuList.map(item => {
					if (!menuList.some(subMenuItem => subMenuItem.parent_id === item.menu_id)) {
						item.isLeafNode = true
					}
				})
				// 删除无权限访问的菜单
				if (!role.includes('admin')) {
					menuList = menuList.filter(item => {
						if (item.isLeafNode) {
							if (item.permission && item.permission.length) {
								return item.permission.some(item => permission.indexOf(item) > -1)
							}
							return false
						}
						return true
					})
				}
				return buildMenus(menuList)
			},
			removeDisabledDynamicMenu() {
				let tempItems = []
				this.dynamicMenuItems.forEach((item) => {
					if (this.subMenuChildrens.findIndex(val => val.menu_id == item.menu_id) != -1) {
						tempItems.push(item);
					}
				});
				this.SET_DYNAMIC_MENU_ITEM(tempItems)
			},
			reload(e) {
				//#ifndef H5
				this.$router.push({
					path: e,
				});
				//#endif
				//#ifdef H5
				window.location.reload();
				//#endif
			},
			load() {
				// 旧
				// this.userMenu = uni.getStorageSync("userMenu");
				// this.pushSubmenuChildren(this.userMenu)
				
				console.log("load");
				let roles = uni.getStorageSync("userInfo")['roles']; // 假设从存储中获取用户角色
				this.userMenu = this.filterArray(this.staticMenu, roles);
				// console.log('cMenu', JSON.stringify(this.userMenu), roles)
				this.pushSubmenuChildren(this.userMenu);
				this.loaded = true;
			},
			searchMenu(queryString, cb) {
				const createFilter = (queryString) => {
					return (restaurant) => {
						console.log("restaurant:", restaurant);
						return (
							restaurant.text.toLowerCase().indexOf(queryString.toLowerCase()) === 0
						)
					}
				}

				const results = queryString ?
					this.subMenuChildrens.filter(createFilter(queryString)) :
					this.subMenuChildrens
				// call callback function to return suggestions
				cb(results)
			},
			searchMenuSelect(item) {
				this.select(item.menu_id, "")
				console.log(item)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.sidebar {
		position: fixed;
		top: calc(var(--top-window-height) - 20px); // useless
		width: 240px;
		bottom: 0px;
		// height: calc(100vh - (var(--top-window-height)));
		height: calc(100vh - (var(5px)));
		box-sizing: border-box;
		border-right: 1px solid darken($left-window-bg-color, 8%);
		background-color: $left-window-bg-color;
		padding-bottom: 10px;
	}

	/* #ifdef H5 */
	.sidebar ::-webkit-scrollbar {
		display: none;
		// scrollbar-width: thin;
	}

	/* #endif */

	.title {
		margin-left: 5px;
	}

	.logo {
		overflow: hidden;
		width: 180px;
		height: 100px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.headImg {
		// width: 100%;
		height: 100px;
		transition: all .35s;
		display: flex;
		-webkit-align-items: center;
		align-items: center;
		width: var(--window-left);
	}

	.menu {
		overflow: overlay;
		height: calc(100% - 100px);
		overflow-x: hidden;
		// background-color: #fff;
		border: none;
	}

	.menu::-webkit-scrollbar {
		display: none;
	}

	::v-deep {
		.el-menu-item.is-active {
			background-color: #1890ff !important;
			// scroll-behavior: smooth;
		}

		.el-submenu.is-opened .el-submenu__title * {
			color: rgba(255, 255, 255, 1) !important;
		}

		.el-menu .el-menu--inline {
			background-color: #000c17 !important;
		}

		.el-menu-item {
			background-color: transparent !important;
		}

		// .el-menu-item.is-active::after {
		// 	content: " ";
		// 	position: absolute;
		// 	right: 0;
		// 	width: 0.3125rem;
		// 	height: 1.25rem;
		// 	background-color: #e8b339;
		// 	top: 50%;
		// 	transform: translateY(-50%);
		// }

		.el-menu-item {
			min-width: 0 !important;
		}

		.el-input__wrapper {
			background-color: #001529;

			.is-focus {
				box-shadow: 0 0 0 1px #002446;
				// --el-input-focus-border: #ff0000 !important;
			}

			// box-shadow: 0 0 0 1px #0057af;
		}

	}


	.aside {
		height: 100%;
		min-height: 100vh;
		overflow-x: hidden;
		overflow-y: hidden;
		transition: all .35s;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
		border: none;
	}

	.icon-margin {
		margin-right: 5px;
	}

	.search-menu-box {
		margin: 5px 2px;

	}

	.my-autocomplete {
		background-color: #001529 !important;
	}

	.my-autocomplete li {
		line-height: normal;
		padding: 7px;
	}

	.my-autocomplete li .name {
		text-overflow: ellipsis;
		overflow: hidden;
	}

	.my-autocomplete li .addr {
		font-size: 12px;
		color: #b4b4b4;
	}

	.my-autocomplete li .highlighted .addr {
		color: #ddd;
	}
</style>